package io.github.cisumer.wcfbin4j.nodes.texts;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

import io.github.cisumer.wcfbin4j.nodes.TextRecord;
import io.github.cisumer.wcfbin4j.util.Base64TextCodec;

/**
 * 使用Base64编码储存内容。内容实质是二进制，可定义codec对内容进行解码操作
 * @author github.com/cisumer
 *
 */
public class Bytes8Text extends TextRecord<String> {
	public static Base64TextCodec<?> codec;
	@Override
	public int getType() {
		return 0xA0;
	}

	@Override
	public void parse(InputStream is) throws IOException {
		int len = is.read();
		byte[] bs = new byte[len];
		is.read(bs);
		this.value = Base64.getEncoder().encodeToString(bs);
	}

	@Override
	public void renderContent(OutputStream os) throws Exception {
		byte[] bs = Base64.getDecoder().decode(value);
		os.write((byte) bs.length);
		os.write(bs);
	}
	
	public String toXML(){
		if(codec!=null)
			return (String) codec.codec(value);
		return super.toXML();
	}
}
